import React, { useState } from 'react';
import { ScrollView } from 'react-native';
import {
  List,
  TextareaItem,
  Checkbox,
  Button,
  Toast,
} from '@ant-design/react-native';
import ReleaseJobStore from './releaseJobStore';
import UserStore from '@/stores/userStore';

function JobReturnPage({ navigation, route }) {
  const userStore = UserStore.useStore();
  const [retCates, setRetCates] = useState([
    {
      key: 'material',
      text: '航材',
      checked: false,
    },
    {
      key: 'equipment',
      text: '工具设备',
      checked: false,
    },
    {
      key: 'human',
      text: '人力',
      checked: false,
    },
    {
      key: 'aog',
      text: '停场时间',
      checked: false,
    },
    {
      key: 'etc',
      text: '其他',
      checked: false,
    },
  ]);
  const [paraMemo, setParaMemo] = useState('');
  const rjStore = ReleaseJobStore.useStore();
  const handleRemarkChange = (val) => {
    setParaMemo(val);
  };
  const handleReturn = async () => {
    const paraChecks = retCates
      // .filter((rtc) => rtc.checked)
      .map((rtc) => (rtc.checked === true ? 1 : 0))
      .join(';');
    if (!paraChecks) {
      Toast.fail('选择退单原因');
      return;
    }
    const res = await rjStore.returnTask(
      userStore.user.LoginName,
      route.params.taskTid,
      paraChecks,
      paraMemo,
    );
    if (res.errorCode) {
      Toast.fail(res.errorMsg);
      return;
    }
    navigation.goBack();
  };
  return (
    <>
      <ScrollView keyboardShouldPersistTaps={'always'} nestedScrollEnabled>
        <List renderHeader="退单类别">
          {retCates.map((retcat) => (
            <Checkbox.CheckboxItem
              key={retcat.key}
              checked={retcat.checked}
              onChange={(event) => {
                setRetCates(
                  retCates.map((retc) => {
                    if (retc.key === retcat.key) {
                      return { ...retc, checked: event.target.checked };
                    }
                    return retc;
                  }),
                );
              }}
            >
              {retcat.text}
            </Checkbox.CheckboxItem>
          ))}
          <List.Item>备注</List.Item>
          <TextareaItem
            rows={4}
            value={paraMemo}
            onChange={handleRemarkChange}
          />
        </List>
      </ScrollView>
      <Button
        type="primary"
        onPress={handleReturn}
        loading={rjStore.returnTask.loading}
      >
        退单
      </Button>
    </>
  );
}

JobReturnPage.routeName = 'JobReturn';
JobReturnPage.permission = 'RJobReturn';
export default JobReturnPage;
